package com.wang.tool.monitor.weaver;


import com.alibaba.fastjson.JSONObject;
import com.wang.tool.common.result.ApiResult;
import com.wang.tool.monitor.core.LinkInfo;
import com.wang.tool.monitor.core.MonitorInfo;

/**
 * @Description
 * @Author shaopeng
 * @Date 2023/5/23
 * @Version 1.0
 */
public class ApiResultTypeWeaver implements TypeWeaver<ApiResult> {
    
    @Override
    public Class<ApiResult> point() {
        return ApiResult.class;
    }

    @Override
    public void weaver(MonitorInfo<ApiResult> monitorInfo) throws Throwable {
        ApiResult result = monitorInfo.getResult();
        if (result.getStatus() != null) {
            monitorInfo.setStatus(result.getStatus());
        }
        if (!result.isSuccess()) {
            monitorInfo.markImplicitError();
        }

        LinkInfo parent = monitorInfo.getParent();
        boolean root = parent == null;
        if (!root) {
            return;
        }
//        debug || 出错了
        boolean needProfiler = monitorInfo.isDebug() || !result.isSuccess();
        if (!needProfiler) {
            return;
        }
        JSONObject extInfo = result.getExt();
        if (extInfo==null) {
            extInfo = new JSONObject(1);
            result.setExt(extInfo);
        }
        extInfo.computeIfAbsent("_profiler", o -> monitorInfo.getLink().toProfilerString());
    }
}
